using AutoMapper;
using MediatR;
using RBAC.Domain.Department;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.MaterialFile.Department;
using System.Transactions;
using Microsoft.Extensions.Logging;

namespace RBAC.Write.Api.Application.Handler.ERP.MaterialFile.Department
{
    /// <summary>
    /// 更新部门处理类
    /// </summary>
    public class UpdateDepartmentHandler : IRequestHandler<UpdateDepartmentCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<DepartmentManagement> departmentRepository;
        private readonly ILogger<UpdateDepartmentHandler> logger;
        private readonly IMapper mapper;

        public UpdateDepartmentHandler(
            IBaseRepository<DepartmentManagement> departmentRepository,
            ILogger<UpdateDepartmentHandler> logger,
            IMapper mapper)
        {
            this.departmentRepository = departmentRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 更新部门
        /// </summary>
        /// <param name="request">更新部门请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public Task<APIResult<bool>> Handle(UpdateDepartmentCommand request, CancellationToken cancellationToken)
        {
            APIResult<bool> res = new APIResult<bool>();

            try
            {
                logger.LogInformation("开始更新部门: ID={Id}, DepartmentName={DepartmentName}", request.Id, request.DepartmentName);

                // 1. 数据验证 - 与创建功能保持一致
                if (request.Id <= 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "部门ID不能为空";
                    logger.LogWarning("部门ID验证失败");
                    return Task.FromResult(res);
                }

                if (string.IsNullOrWhiteSpace(request.DepartmentName))
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "部门名称不能为空";
                    logger.LogWarning("部门名称验证失败");
                    return Task.FromResult(res);
                }

                if (request.DepartmentName.Length > 50)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "部门名称长度不能超过50个字符";
                    logger.LogWarning("部门名称长度验证失败: {Length}", request.DepartmentName.Length);
                    return Task.FromResult(res);
                }

                if (request.Status != 0 && request.Status != 1)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "部门状态只能是0(禁用)或1(启用)";
                    logger.LogWarning("部门状态验证失败: {Status}", request.Status);
                    return Task.FromResult(res);
                }

                // 2. 检查部门是否存在
                var existingDepartment = departmentRepository.QueryFirstOrDefault<DepartmentManagement>(
                    "SELECT * FROM Department WHERE Id = @Id AND IsDeleted = false", 
                    new { Id = request.Id });
                
                if (existingDepartment == null)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "部门不存在";
                    logger.LogWarning("部门不存在: {Id}", request.Id);
                    return Task.FromResult(res);
                }

                // 3. 检查部门名称是否与其他部门冲突（排除当前部门）
                var nameConflict = departmentRepository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM Department WHERE DepartmentName = @DepartmentName AND Id != @Id AND IsDeleted = false", 
                    new { DepartmentName = request.DepartmentName, request.Id });
                
                if (nameConflict > 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "部门名称已存在";
                    logger.LogWarning("部门名称冲突: {DepartmentName}, 当前ID: {Id}", request.DepartmentName, request.Id);
                    return Task.FromResult(res);
                }

                // 4. 验证上级部门是否存在（如果有上级部门）
                if (request.ParentId.HasValue && request.ParentId.Value > 0)
                {
                    // 检查上级部门是否存在
                    var parentDepartment = departmentRepository.QueryFirstOrDefault<int>(
                        "SELECT COUNT(1) FROM Department WHERE Id = @Id AND IsDeleted = false", 
                        new { Id = request.ParentId.Value });
                    
                    if (parentDepartment == 0)
                    {
                        res.Code = APIEnums.Error;
                        res.Msg = "指定的上级部门不存在";
                        logger.LogWarning("上级部门验证失败: {ParentId}", request.ParentId.Value);
                        return Task.FromResult(res);
                    }

                    // 检查是否试图将自己设置为自己的上级
                    if (request.ParentId.Value == request.Id)
                    {
                        res.Code = APIEnums.Error;
                        res.Msg = "部门不能设置为自己的上级部门";
                        logger.LogWarning("循环引用验证失败: 部门ID={Id} 不能设置为自己的上级", request.Id);
                        return Task.FromResult(res);
                    }
                }

                // 5. 更新部门信息
                using (TransactionScope tran = new TransactionScope())
                {
                    try
                    {
                        // 构建更新SQL，与创建功能字段保持一致（移除UpdateTime字段，因为数据库中没有该字段）
                        var sql = @"UPDATE Department SET 
                                    DepartmentName = @DepartmentName,
                                    ParentId = @ParentId,
                                    Sort = @Sort,
                                    Status = @Status
                                  WHERE Id = @Id AND IsDeleted = false";
                        
                        var parameters = new 
                        {
                            request.Id,
                            request.DepartmentName,
                            request.ParentId,
                            request.Sort,
                            request.Status
                        };
                        
                        var affectedRows = departmentRepository.Execute(sql, parameters);
                        
                        if (affectedRows <= 0)
                        {
                            res.Code = APIEnums.Error;
                            res.Msg = "部门更新失败，可能部门不存在或已被删除";
                            logger.LogWarning("部门更新失败: {Id}", request.Id);
                            return Task.FromResult(res);
                        }

                        tran.Complete();

                        res.Code = APIEnums.Success;
                        res.Data = true;
                        res.Msg = "部门更新成功";

                        logger.LogInformation("部门 {DepartmentName} 更新完成，ID: {Id}", 
                            request.DepartmentName, request.Id);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "更新部门过程中发生错误: {Message}", ex.Message);
                        res.Code = APIEnums.Error;
                        res.Msg = "更新部门失败";
                        res.Data = false;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新部门失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "更新部门失败";
                res.Data = false;
            }

            return Task.FromResult(res);
        }
    }
}